package com.mars.admin.modules.h5.controller;

import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSON;
import com.mars.admin.common.utils.Coordinategen;
import com.mars.admin.common.utils.R;
import com.mars.admin.modules.h5.entity.*;
import com.mars.admin.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/h5")
public class H5LoginController {

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R loginh5(@RequestBody UserInfoEntity userInfoEntity) {

        if (StringUtils.isEmpty(userInfoEntity.getUsername()) || StringUtils.isEmpty(userInfoEntity.getPassword())) {
            return R.error("用户名或密码不能为空");
        }

        try{
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userInfoEntity.getUsername(), userInfoEntity.getPassword());
            subject.login(token);
        }catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        }catch (LockedAccountException e) {
            return R.error("账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }

        return R.ok();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String h5logout() {
        ShiroUtils.logout();
        return "redirect:/h5/login.html";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView h5index() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/h5/login");
        return modelAndView;
    }

    @RequestMapping(value = "/maintainmap", method = RequestMethod.GET)
    public ModelAndView getMaintainMap(HttpServletRequest httpServletRequest) {

        String username = httpServletRequest.getParameter("username");
//        Coordinategen coordinategen = new Coordinategen();
//        List<Entity> entityList = coordinategen.getSensorNeedfix(username);
//
//        List<SensorDtoEntity> sensorDtoEntities = new ArrayList<SensorDtoEntity>();
//        for (Entity entity:entityList) {
//            SensorDtoEntity sensorDtoEntity = new SensorDtoEntity();
//            sensorDtoEntity.setLongtitude(entity.getBigDecimal("sensor_longitude"));
//            sensorDtoEntity.setAtitude(entity.getBigDecimal("sensor_latitude"));
//            sensorDtoEntity.setSensortype(entity.getStr("code_name"));
//            sensorDtoEntity.setElectricity(entity.getBigDecimal("battery_status"));
//            sensorDtoEntity.setAddress(entity.getStr("sensor_location"));
//            sensorDtoEntities.add(sensorDtoEntity);
//        }

//        StringBuffer pointbuffer = new StringBuffer();
//        pointbuffer.append("[");
//        for (Entity entity:entityList) {
//            pointbuffer.append("[");
//            pointbuffer.append(entity.getBigDecimal("sensor_longitude"));
//            pointbuffer.append(",");
//            pointbuffer.append(entity.getBigDecimal("sensor_latitude"));
//            pointbuffer.append(",\"电量：");
//            pointbuffer.append(entity.getBigDecimal("battery_status"));
//            pointbuffer.append("|地址：");
//            pointbuffer.append(entity.getStr("sensor_location"));
//            pointbuffer.append("\"],");
//        }
//
//        pointbuffer.deleteCharAt(pointbuffer.length()-1);
//        pointbuffer.append("]");
//
////        System.out.println(pointbuffer);
//        String allpointneedfix = pointbuffer.toString();
        ModelAndView modelAndView = new ModelAndView();
//        String allpointneedfix = JSON.toJSONString(sensorDtoEntities);

//        System.out.println(allpointneedfix);
        modelAndView.addObject("username",username);
        modelAndView.setViewName("/h5/maintainmapffk");
        return modelAndView;
    }

    @RequestMapping(value = "/getsensorlist", method = RequestMethod.GET)
    public R getSensorlist(HttpServletRequest httpServletRequest) {

        String username = httpServletRequest.getParameter("username");
        Coordinategen coordinategen = new Coordinategen();
        List<Entity> entityList = coordinategen.getSensorNeedfix(username);

        List<SensorDtoEntity> sensorDtoEntities = new ArrayList<SensorDtoEntity>();
        for (Entity entity:entityList) {
            SensorDtoEntity sensorDtoEntity = new SensorDtoEntity();
            sensorDtoEntity.setLongtitude(entity.getBigDecimal("sensor_longitude"));
            sensorDtoEntity.setAtitude(entity.getBigDecimal("sensor_latitude"));
            sensorDtoEntity.setSensortype(entity.getStr("code_name"));
            sensorDtoEntity.setElectricity(entity.getBigDecimal("battery_status"));
            sensorDtoEntity.setAddress(entity.getStr("sensor_location"));
            sensorDtoEntity.setSensorid(entity.getInt("id"));
            sensorDtoEntities.add(sensorDtoEntity);
        }

        return R.ok().put("sensorlist", sensorDtoEntities);
    }

    @RequestMapping(value = "/getuser", method = RequestMethod.GET)
    public R getUser(HttpServletRequest httpServletRequest) {

        String username = httpServletRequest.getParameter("username");
        Coordinategen coordinategen = new Coordinategen();
        List<Entity> entityList = coordinategen.getUser(username);

        ServiceDto serviceDto = new ServiceDto();
        serviceDto.setId(entityList.get(0).getInt("id"));
        serviceDto.setRealname(entityList.get(0).getStr("realname"));
        serviceDto.setWhgroup(entityList.get(0).getStr("whgroup"));

        return R.ok().put("serviceengineer", serviceDto);
    }

    @RequestMapping(value = "/getbattery", method = RequestMethod.GET)
    public R getBattery(HttpServletRequest httpServletRequest) {

        String username = httpServletRequest.getParameter("username");
        Coordinategen coordinategen = new Coordinategen();
        List<Entity> entityList = coordinategen.getBattery(username);
        List<Entity> entityList2 = coordinategen.getAllBattlist();

        List<BatteryNumDto> batteryNumZero = new ArrayList<BatteryNumDto>();
        List<BatteryNumDto> batteryNumDtoList = new ArrayList<BatteryNumDto>();
        List<String> batteryNumDtoList2 = new ArrayList<String>();
        for (Entity entity:entityList) {
            BatteryNumDto batteryNumDto = new BatteryNumDto();
            batteryNumDto.setBatterytype(entity.getStr("code_name"));
            batteryNumDtoList2.add(entity.getStr("code_name"));
            batteryNumDto.setBattnum(entity.getInt("battnums"));
            batteryNumDtoList.add(batteryNumDto);
        }

        for (Entity entity:entityList2) {
            if (batteryNumDtoList2.contains(entity.getStr("code_name"))) {
                //do nothing
            } else {
                BatteryNumDto batteryNumDto = new BatteryNumDto();
                batteryNumDto.setBatterytype(entity.getStr("code_name"));
                batteryNumDto.setBattnum(0);
                batteryNumZero.add(batteryNumDto);
            }
        }

        batteryNumDtoList.addAll(batteryNumZero);

        return R.ok().put("batterylist", batteryNumDtoList);
    }

    @RequestMapping(value = "/gettoolist", method = RequestMethod.GET)
    public R getToollist(HttpServletRequest httpServletRequest) {

        String username = httpServletRequest.getParameter("username");
        Coordinategen coordinategen = new Coordinategen();
        List<Entity> entityList = coordinategen.getToolist(username);

        List<String> toolListDtos = new ArrayList<String>();
        for (Entity entity:entityList) {
            toolListDtos.add(entity.getStr("code_name"));
        }

        List<Entity> alltools = coordinategen.getAllToolist();
        List<ToolListDto> alltoolListDtos = new ArrayList<ToolListDto>();
        List<ToolListDto> nonumlist = new ArrayList<ToolListDto>();
        for (Entity entity:alltools) {
            ToolListDto toolListDto = new ToolListDto();
            toolListDto.setToolname(entity.getStr("code_name"));
            if (toolListDtos.contains(toolListDto.getToolname())) {
                toolListDto.setIsneed("1");
                alltoolListDtos.add(toolListDto);
            } else {
                toolListDto.setIsneed("0");
                nonumlist.add(toolListDto);
            }
        }
        alltoolListDtos.addAll(nonumlist);

//        HashMap<String,Object> allhm = new HashMap<String,Object>();
//        allhm.put("toollist", toolListDtos);
//        allhm.put("alltoollist", alltoolListDtos);
        return R.ok().put("toollist", alltoolListDtos);

    }

    @RequestMapping(value = "/updatebattstatus", method = RequestMethod.GET)
    public R updateBattstatus(HttpServletRequest httpServletRequest) {

        String username = httpServletRequest.getParameter("username");
        String sensorid = httpServletRequest.getParameter("sensorid");
        Coordinategen coordinategen = new Coordinategen();
        int updaterows = coordinategen.updateBattstatus(username,sensorid);

        return R.ok().put("updaterows", updaterows);
    }
}
